<?php

namespace Admin\Controller;
use User\Api\UserApi;

/**
 * 后台用户控制器
 *
 */
class MemberController extends AdminController {

    /**账号列表
     * @author leiying
     */
    public function index(){
        $limit = LIMIT;
        $get = I('post.');

        $search_data = array();//筛选数据
        $where = array();//条件

        if(IS_POST){
            session('searchdata_memberList',$get);
        }else{
            if(empty(I('get.p'))){
                session('searchdata_memberList',null);
            }
            $get = $search_data = session('searchdata_memberList');
        }
        //搜索条件：
        if(isset($get['uid']) && $get['uid'] != ''){
            $search_data['uid'] = trim($get['uid']);
            $where['uid'] = array('eq',$search_data['uid']);
        }
        if(isset($get['nickname']) && $get['nickname'] != ''){
            $search_data['nickname'] = trim($get['nickname']);
            $where['nickname'] = array('like','%'.$search_data['nickname'].'%');
        }

        if(isset($get['d_id']) && $get['d_id'] != '' && $get['d_id'] != 'all'){
            $search_data['d_id'] = trim($get['d_id']);
            $where['d_id'] = array('eq',$search_data['d_id']);
        }

        $where['a.status']  =   array('egt',0);

        $count = M('member')->alias('a')->where($where)->count();
        $Page = new  \Think\Page($count, $limit);// 实例化分页类 传入总记录数

        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');
        $Page->setConfig('last', '末页');
        $Page->setConfig('first', '首页');
        $Page->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
        $show = $Page->show();// 分页显示输出
        $this->assign('_page', $show);// 赋值分页输出

        $departments = M('department')->order("add_time desc")->select();
        $this->assign("departments",$departments);

        $list = M('member')->alias('a')
            ->field('a.*,c.title,d.name depart_name,e.mobile')
            ->join(C('DB_PREFIX').'auth_group_access b on a.uid = b.uid','left')
            ->join(C('DB_PREFIX').'auth_group c on b.group_id = c.id','left')
            ->join(C('DB_PREFIX').'department d on a.d_id = d.id','left')
            ->join(C('DB_PREFIX').'ucenter_member e on a.uid = e.id','left')
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order("uid desc")
            ->select();
        $this->assign('lists', $list);
        $this->assign('searchs',$search_data);
        $p = I('get.p',"1");
        $this->assign("p",$p);
        $this->display();
    }

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname(){
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display();
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname(){
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User   =   new UserApi();
        $uid    =   $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member =   D('Member');
        $data   =   $Member->create(array('nickname'=>$nickname));
        if(!$data){
            $this->error($Member->getError());
        }

        $res = $Member->where(array('uid'=>$uid))->save($data);

        if($res){
            $user               =   session('user_auth');
            $user['username']   =   $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        }else{
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword(){
        if(I('post.btn')){$this->success('');}
        $this->meta_title = '修改密码';
        $this->display();
    }

    /**修改密码
     * @author leiying
     */
    public function updatePwd(){
        if(I('post.btn')){$this->success('');}
        $this->display();
    }


    /**修改密码提交
     * @author leiying
     */
    public function submitPassword(){

        //获取参数
        $password   =   I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api    =   new UserApi();
        $res    =   $Api->updateInfo(UID, $password, $data);
        if($res['status']){
            $this->success('修改密码成功！');
        }else{
            $this->error($res['info']);
        }
    }

    /**
     * 用户行为列表
     * @author huajie <banhuajie@163.com>
     */
    public function action(){
        //获取列表数据
        $Action =   M('Action')->where(array('status'=>array('gt',-1)));
        $list   =   $this->lists($Action);
        int_to_string($list);
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);

        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        $this->display();
    }

    /**
     * 新增行为
     * @author huajie <banhuajie@163.com>
     */
    public function addAction(){
        $this->meta_title = '新增行为';
        $this->assign('data',null);
        $this->display('editaction');
    }

    /**
     * 编辑行为
     * @author huajie <banhuajie@163.com>
     */
    public function editAction(){
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = M('Action')->field(true)->find($id);

        $this->assign('data',$data);
        $this->meta_title = '编辑行为';
        $this->display();
    }

    /**
     * 更新行为
     * @author huajie <banhuajie@163.com>
     */
    public function saveAction(){
        $res = D('Action')->update();
        if(!$res){
            $this->error(D('Action')->getError());
        }else{
            $this->success($res['id']?'更新成功！':'新增成功！', Cookie('__forward__'));
        }
    }

    /**
     * 用户状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('Member','status', $map );
                break;
            case 'resumeuser':
                $this->resume('Member', $map );
                break;
            case 'deleteuser':
                M('auth_group_access')->where($map)->delete();
                M('ucenter_member')->where(array('id'=>array('in',$id)))->delete();
                $this->remove('Member', $map );
                break;
            default:
                $this->error('参数非法');
        }
    }

    public function add($username = '', $d_id = 0,$password = '', $repassword = '', $email = '',$mobile = ""){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            if(empty($d_id)){
                $this->error("请选择所属部门");
            }
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }
            if(empty($mobile)){
                $this->error('手机号码不能为空！');
            }

            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register($username, $password, $email,trim($mobile));
            if(0 < $uid){ //注册成功
                $user = array('uid' => $uid, 'd_id'=>$d_id,'nickname' => $username, 'status' => 1,'reg_time'=>time());
                if(!M('Member')->add($user)){
                    $this->error('用户添加失败！');
                } else {
                    $this->success('用户添加成功！',U('index'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            /*获取部门*/
            $departments = M("department")->order("add_time desc")->select();
            $this->assign("departments",$departments);
            $this->display();
        }
    }

    /**修改手机号码
     * @author leiying
     */
    public function changeField(){
        $post = I('post.');
        if(!isset($post["id"]) || empty($post["id"])){
            $this->error("请选择要操作的数据");
        }
        $field = isset($post["field"])?trim($post["field"]):"";
        if(empty($field)){$this->error("请选择要操作的数据");}
        $value = isset($post["value"])?trim($post["value"]):"";
        if(empty($value)){$this->error("手机号码不能为空");}

//        $User   =   new UserApi;
//        $res    =   $User->checkMobile($value);

        $data = array($field => $value);
        $res = D("UcenterMember")->create($data);
        if($res){
            $res = D("UcenterMember")->where(array('id'=>$post['id']))->save($res);
            if($res){
                $this->success("修改成功");
            }else{
                $this->error("修改失败");
            }
        }else{
            $this->error(D("UcenterMember")->getError());
        }

    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

}
